import React from 'react';
import CheckBox from './checkbox';
import "babel-polyfill";

export default class CheckBoxGroup extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            opts: this.props.options
        };
        this.handleClick = this.handleClick.bind(this);
        this.renderOpts = this.renderOpts.bind(this);
        this.handleChange = this.handleChange.bind(this)
    }
    static propTypes = {
        name: React.PropTypes.string.isRequired,
        btnType: React.PropTypes.string,
        hasAllCheck: React.PropTypes.array

    };
    handleChange(target,opt){
        let newOpts = this.state.opts;
        newOpts[target] = opt;
        this.setState({
            opts: newOpts
        })
    }
    /**
     *  提交新的数据到父组件的时机：实时提交、最后一起提交
     *  由props.sendType决定：
     *  props.sendType == 'rt' => real time 实时提交
     *  props.sendType == 'fin' => final 最后提交
     */
    componentWillUnmount(){
        if(this.props.sendType === 'fin'){
            this.props.saveData('CATE',this.state.opts)
        }
    }
    renderOpts(o,all){
        let opts = o || "没数据";
        let optDOM = [];
        if(all[0]){
            optDOM.push(
                <CheckBox key={"cate_all"}
                          value={all[1]}
                          id={'checkedall'}
                          checked={this.props.allChecked}
                          name={all[1]}
                          onChange={this.handleChange}
                />
            )
        }

        for(let opt in opts){
            optDOM.push(
                <CheckBox key={"cate_"+opt}
                          value={opt}
                          checked={opts[opt].checked}
                          name={opts[opt].name}
                          other={opts[opt].other}
                          id={opt}
                          all={this.props.allChecked}
                          onChange={this.handleChange}
                />
            )
        }
        return optDOM
    }
    handleClick(){}
    render(){
        let hasAllCheck = (this.props.hasAllCheck === undefined || typeof this.props.hasAllCheck[0] !== 'boolean')?[true,'全部']:this.props.hasAllCheck;
        return (
            <div className="checkbox-group" onClick={this.handleClick}>

                {this.renderOpts(this.state.opts,hasAllCheck)}
            </div>
        )
    }
}